﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using MaxStoreErp.Core.BaseClasses;
using MaxStoreErp.Core.Commands;
using MaxStoreErp.Core.Extensions;
using MaxStoreErp.Core.Interfaces;
using MaxStoreErp.Core.Threading;
using MaxStoreShop.Core.Ui;
using MaxStoreShop.Domain.Directories;
using MaxStoreShop.Logic.ServicesContracts.Directories;
using Microsoft.Practices.Unity;
using Microsoft.Win32;

namespace MaxStoreShop.CoreModule.Users
{
    internal class UsersPresenter : PresenterBase<UsersView, UsersViewModel>, IToolBarProvider
    {
        [Dependency]
        public IUserService UserService { get; set; }

        public ReadOnlyCollection<FrameworkElement> ToolBarItems { get; private set; }

        protected override void OnDataLoading()
        {
            base.OnDataLoading();
            ViewModel.Users = UserService.GetUsers().ToObservableCollection();
        }

        protected override void OnViewModelSet()
        {
            base.OnViewModelSet();
            ViewModel.ChangePhotoCommand = new RelayCommand(ChangePhoto, () => ViewModel.SelectedUser != null);
            ViewModel.ChangePasswordCommand = new RelayCommand(ChangePassword, ()=>ViewModel.SelectedUser != null);
        }

        async void ChangePassword()
        {
            var changePasswordDialog = Container.Resolve<ChangePasswordDialog.ChangePasswordDialogPresenter>();
            changePasswordDialog.ViewModel.SelectedUser = ViewModel.SelectedUser;
            await UserMessage.CustomDialogAsync(changePasswordDialog.GetDocumentView());
        }

        void OnRowDeleting(object sender, object entity, RowDeletingEventArgs arg)
        {
            try
            {
                var user = entity as StoreUser;
                if (user == null)
                    return;

                if (!user.IsNew())
                    UserService.DeleteUser(user);
            }
            catch (Exception exception)
            {
                arg.Cancel = true;
                LogAndShowError("Ошибка удаления пользователя", exception);
            }
        }

        void OnRowChanged(object sender, DataGridRowEditEndingEventArgs dataGridRowEditEndingEventArgs)
        {
            try
            {
                var user = dataGridRowEditEndingEventArgs.Row.Item as StoreUser;
                if (user != null && user.IsNew())
                {
                    UserMessage.InfoMessageAsync(
                        string.Format("Для пользователя {0} задан пароль по-умолчанию: 1234", user.DisplayName),
                        "Создание пользователя");
                    user.SecretCode = "1234";
                }
                UserService.SaveUser(user);
            }
            catch (Exception exception)
            {
                dataGridRowEditEndingEventArgs.Cancel = true;
                LogAndShowError("Ошибка изменения данных пользователя", exception);
            }
        }

        void ChangePhoto()
        {
            var ofd = new OpenFileDialog
            {
                Filter = "Изображения|*.bmp;*.jpg;*.png",
                Title = "Загрузка изображения пользователя"
            };

            try
            {
                if (ofd.ShowDialog() != true)
                    return;

                ReadFotoToSelectedUser(ofd.FileName);
                UserService.SaveUser(ViewModel.SelectedUser);
            }
            catch (Exception exception)
            {
                LogAndShowError(string.Format("Ошибка смены фотографии пользователя {0}", ViewModel.SelectedUser.DisplayName), exception);
            }
        }

        void ReadFotoToSelectedUser(string fileName)
        {
            using (
                var reader =
                    new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                var imageBytes = new byte[reader.BaseStream.Length];
                imageBytes = reader.ReadBytes(imageBytes.Length);
                ViewModel.SelectedUser.FotoRaw = imageBytes;
                reader.Close();
            }
        }

        protected override void OnViewSet()
        {
            base.OnViewSet();
            View.MainDataGrid.OnRowChanged += OnRowChanged;
            View.MainDataGrid.OnRowDeleting += OnRowDeleting;
            ThreadHelper.SafeCall(() =>
            {
                ToolBarItems =
                    new ReadOnlyCollection<FrameworkElement>(View.MyToolBar.Items.Cast<FrameworkElement>().ToList());
            });
        }
    }
}
